package cn.webrx.controller;

import cn.webrx.entity.User;
import cn.webrx.service.CaptchaService;
import cn.webrx.service.UserService;
import cn.webrx.vo.UserLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    CaptchaService es;
    @Autowired
    UserService us;


    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody UserLoginVo uv) {

        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "message");

        //查询数据库 检查验证码
        //QueryWrapper<Captcha> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("id", uv.getId());
        //Captcha c1 = es.getOne(queryWrapper);
        //System.out.println(c1);
        //
        //System.out.println(es.getCaptcha(uv.getId()));

        //根据验证码id查询数据库 验证码值如果为null 则验证码过期
        String c1 = es.getCaptcha(uv.getId());
        if (c1 == null || !c1.equalsIgnoreCase(uv.getValue())) {
            //验证码错误
            map.put("msg", "验证码错误");
            map.put("code", 400);
        } else {
            //验证码正确
            //map.put("msg", "验证码正确");
            //检查账号和密码 用户的状态
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            Map<String, Object> mm = new HashMap<>();
            mm.put("account", uv.getAccount());
            wrapper.allEq(mm);
            User user = us.getOne(wrapper);
            PasswordEncoder pe = new BCryptPasswordEncoder();
            if (user == null) {
                map.put("code", 300);
                map.put("msg", "登录失败，账号错误");
            } else if(pe.matches(uv.getPassword(),user.getPassword())) {
                map.put("code", 200);
                map.put("msg", "登录成功，生成令牌"+user.getName());
                System.out.println("登录成功");
            } else {
                map.put("code", 300);
                map.put("msg", "登录失败，密码错误");
            }
        }
        return map;
    }


    public Map<String, Object> loginback(@RequestBody Map<String, Object> v) {
        System.out.println(v);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "message");

        return map;
    }
}
